package com.javaweb.config;

import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;

/**
 * @desc:
 * @author: Ping
 * @date: 2024/9/24 15:54
 */
@Configuration
@PropertySource("classpath:db.properties")
@Slf4j
public class ResourceConfig {
    @Value("${jdbc.driver}")
    private String driver ;
    @Value("${jdbc.url}")
    private String url ;
    @Value("${jdbc.username}")
    private String username ;
    @Value("${jdbc.password}")
    private String password ;


    @Value("${hikari.maximum-pool-size}")
    private int maximumPoolSize;

    @Value("${hikari.minimum-idle}")
    private int minimumIdle;

    @Value("${hikari.idle-timeout}")
    private long idleTimeout;

    @Value("${hikari.connection-timeout}")
    private long connectionTimeout;

    @Value("${hikari.max-lifetime}")
    private long maxLifetime;
    @Value("${hikari.pool-name}")
    private  String poolName ;

    @Bean
    public Connection getConnection() {
        Connection conn = null ;
        try {
            Class.forName(driver) ;
            conn = DriverManager.getConnection(url, username, password) ;
        } catch (Exception e) {
            log.error("jdbc connection was built failure.") ;
        }
        return conn ;
    }


    public DataSource basicDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(this.driver);
        dataSource.setUrl(this.url);
        dataSource.setUsername(this.username);
        dataSource.setPassword(this.password);
        return dataSource;
    }

    @Bean
    public DataSource dataSource() {
        //从db.properties中配置 HikariDatasource
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setDriverClassName(this.driver);
        dataSource.setJdbcUrl(this.url);
        dataSource.setUsername(this.username);
        dataSource.setPassword(this.password);

        // 配置HikariCP的参数
        dataSource.setMaximumPoolSize(maximumPoolSize);
        dataSource.setMinimumIdle(minimumIdle);
        dataSource.setIdleTimeout(idleTimeout);
        dataSource.setConnectionTimeout(connectionTimeout);
        dataSource.setMaxLifetime(maxLifetime);

        // 可以根据需要设置其他HikariCP的配置参数
        dataSource.setPoolName(poolName);

        return dataSource ;
    }
    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

}
